#! /usr/bin/env python
# -*- coding: utf-8 -*-

# *************************************************************
#     Filename @  views.py
#       Author @  Huoty
#  Create date @  2015-12-16 20:37:10
#  Description @
# *************************************************************

from flask import Blueprint, render_template, request, session, g, redirect, url_for, flash
from jinja2 import TemplateNotFound
from kwsite import app
from kwsite.lib.krandom import random_str
from kwsite.admin.models import *
from hashlib import sha1
from time import strftime, localtime
from math import ceil

admin = Blueprint('admin', __name__, template_folder='templates')

@admin.route('/', methods = ["GET", "POST"])
def login():
    if request.method == "POST" and valid_login(request.form['username'], request.form['password']):
        last_login = Record.query.get_last_record(session["username"])
        if last_login:
            session["last_login_time"] = last_login.time
            session["last_login_ip"] = last_login.ip
        else:
            session["last_login_time"] = request.remote_addr
            session["last_login_ip"] = u"您是第一次登陆"

        login_ip = request.remote_addr
        login_time = strftime("%Y-%m-%d %X", localtime())
        insert_record(session["username"], login_time, login_ip)

        return redirect(url_for("admin.show_info"))

    try:
        return render_template("login.html")
    except TemplateNotFound:
        abort(404)

@admin.route("/" + random_str(6))
def show_info():
    try:
        return render_template("admin.html")
    except TemplateNotFound:
        abort(404)

@admin.route("/" + random_str(6))
def show_pm_index():
    """page manage of index"""

    try:
        return render_template("pm_index.html")
    except TemplateNotFound:
        abort(404)

@admin.route("/" + random_str(6))
def show_pm_nav():
    """page manage of navigation"""

    page = int( request.args.get('page','1') )  # get 页码 page，如果为空，就给默认值 1
    if page < 1:  # 因为我们返回的page值，不能小于1
        page = 1     # 当小于1时，我们就重新赋值等于1

    NAVS_PER_PAGE = 15  # 每页显示的条数

    paginate = Favorites.query.get_favorites_perpage(page, NAVS_PER_PAGE)

    favorites = paginate.items  # 取出需要显示的数据
    total = ceil(paginate.total / float(NAVS_PER_PAGE))  #数据总条数

    try:
        return render_template('pm_nav.html', pagination = paginate, favorites = enumerate(favorites), total = int(total), cur_page = page)
    except TemplateNotFound:
        abort(404)

@admin.route("/" + random_str(6))
def show_pm_essay():
    """page manage of essays"""

    page = int( request.args.get('page', '1') )  # get 页码 page，如果为空，就给默认值 1
    if page < 1:  # 因为我们返回的page值，不能小于1
        page = 1     # 当小于1时，我们就重新赋值等于1

    ESSAYS_PER_PAGE = 5  # 每页显示的条数

    paginate = Essay.query.get_essays_perpage(page, ESSAYS_PER_PAGE)

    essays = paginate.items  # 取出需要显示的数据
    total = ceil(paginate.total / float(ESSAYS_PER_PAGE))  #数据总条数

    try:
        return render_template('pm_essay.html', pagination = paginate, essays = enumerate(essays), total = int(total), cur_page = page)
    except TemplateNotFound:
        abort(404)

@admin.route("/" + random_str(6))
def show_pm_album():
    """page manage of album"""

    album = Album.query.getall()
    try:
        return render_template("pm_album.html", album = enumerate(album))
    except TemplateNotFound:
        abort(404)

@admin.route("/" + random_str(6) + "@<user_purview>")
def show_user(user_purview = None):
    """user manage of all user"""

    page = int( request.args.get("page", 1) )
    if page < 1:
        page = 1

    USERS_PER_PAGE = 8

    if not user_purview:
        paginate = Administrator.query.get_users_perpage(page, USERS_PER_PAGE)
    else:
        paginate = Administrator.query.get_users_perpage(page, USERS_PER_PAGE, user_purview)

    users = paginate.items
    total = ceil(paginate.total / float(USERS_PER_PAGE))

    try:
        return render_template("um_all.html", pagination = paginate, users = enumerate(users), total = int(total), cur_page = page)
    except TemplateNotFound:
        abort(404)

def valid_login(username, password):
    if len(username) == 0:
        flash("Username is empty")
        return False
    if len(password) == 0:
        flash("Password is empty")
        return False

    password = sha1(password.encode("utf-8")).hexdigest()
    if username != app.config['USERNAME']:
        if not Administrator.query.filter_by(name=username).first():
            flash("Invalid username")
            return False
        elif not Administrator.query.filter_by(name=username, passwd=password).first():
            flash("Invalid password")
            return False
        else:
            session["logged_in"] = True
            session["username"] = username
            return True
    elif password != app.config["PASSWORD"]:
        flash("Invalid password")
        return False
    else:
        session["logged_in"] = True
        session["username"] = username
        return True




# Script starts from here
